package com.kcwl.idea.plugins.gateway.handler;

import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.psi.xml.XmlDocument;
import com.intellij.psi.xml.XmlFile;
import com.intellij.psi.xml.XmlTag;

public class MavenUtil {
    public static String getArtifactId(AnActionEvent e) {
        // 获取当前活动的项目
        VirtualFile currentFile = e.getData(CommonDataKeys.VIRTUAL_FILE);
        VirtualFile parentDirectory = currentFile.getParent();
        String directoryPath = "";
        if (parentDirectory != null) {
            // 这是当前文件所在的目录
            String[] split = parentDirectory.getPath().split("src");
            directoryPath = split[0];
        }
        PsiManager psiManager = PsiManager.getInstance(e.getProject());
        VirtualFile virtualFile = LocalFileSystem.getInstance().findFileByPath(directoryPath + "pom.xml");
        PsiFile psiFile = psiManager.findFile(virtualFile);
        XmlFile xmlFile = (XmlFile) psiFile;
        XmlDocument xmlDocument = xmlFile.getDocument();
        XmlTag rootTag = xmlDocument.getRootTag();
        XmlTag artifactIdTag = rootTag.findFirstSubTag("artifactId");
        return artifactIdTag.getValue().getText();
    }
}
